package com.lkl.service.impl;

import com.lkl.entity.Course;
import com.lkl.mapper.CourseMapper;
import com.lkl.service.CourseService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.concurrent.TimeUnit;

/**
 * @Author: Li
 * @Date: 2024/11/12 20:50
 * @Description:
 */
@Service
public class CourseServiceImpl implements CourseService {
    @Autowired
    private CourseMapper courseMapper;
    @Autowired
    private RedisTemplate redisTemplate;
    
    @Override
    public Course findById(int id) {
        // 先查询redis中是否有这个id的课程
        Course course = getCourseByRedis(id);
        
        if (course != null) {
            System.out.println("从redis查询到id为" + id + "的课程。");
            return course;
        }
        // redis中没有数据，查询mysql并将结果保存到redis
        course = courseMapper.findById(id);
        if (course != null) {
            System.out.println("将id为" + id + "的课程保存到redis。");
            saveToRedis(course);
        }
        
        return course;
    }
    
    @Override
    @Transactional  // 开启事务
    public String updateById(Course course) {
        // 获取课程id
        Integer id = course.getId();
        if (id == null) {
            return "课程id不能为空";
        }
        
        // 先更新mysql
        courseMapper.updateById(course);
        
        // 再删除缓存
        redisTemplate.delete("course:" + id);
        return "更新成功";
    }
    
    // 保存到redis
    private void saveToRedis(Course course) {
        String key = "course:" + course.getId();
        redisTemplate.opsForHash().put(key, "id", course.getId());
        redisTemplate.opsForHash().put(key, "cname", course.getCname());
        redisTemplate.opsForHash().put(key, "credit", course.getCredit());
        redisTemplate.opsForHash().put(key, "department", course.getDepartment());
        redisTemplate.opsForHash().put(key, "content", course.getContent());
        
        // 设置过期时间为6分钟
        redisTemplate.expire(key, 360, TimeUnit.SECONDS);
    }
    
    // 从redis获取Course
    private Course getCourseByRedis(int id) {
        String key = "course:" + id;
        if (redisTemplate.hasKey(key)) {
            Course course = new Course();
            course.setId((Integer) redisTemplate.opsForHash().get(key, "id"));
            course.setCname((String) redisTemplate.opsForHash().get(key, "cname"));
            course.setCredit((Integer) redisTemplate.opsForHash().get(key, "credit"));
            course.setDepartment((String) redisTemplate.opsForHash().get(key, "department"));
            course.setContent((String) redisTemplate.opsForHash().get(key, "content"));
            return course;
        }
        return null;
    }
}




